#include "aoi.h"
#include "bsp.h"
#include "plantform_systick.h"
#include <stdio.h>

int systick_a = 0;
int systick_b = 0;
int press_time = 0;

__weak_symbol void aoi_config(void)
{
}

void aoi_start(struct LCD *lcd)
{
	/* short delay to make sure that the serial monitor was started before we print something */
	int led_flash_cnt = 0;
	delay_ms(200);

	bsp_initial();

	bsp_setKeyPin(1);

aoi_start:
	// lcd power off
	bsp_allio_low();
	delay_ms(10);
	bsp_setVdd(0);
	delay_ms(10);
	bsp_setLed(0);

	// wait key
	press_time = 0;
	while (1) {
		delay_ms(2);

		if (bsp_getKey() == 0) {

			delay_ms(20);
			if (bsp_getKey() == 0) {
				while (bsp_getKey() == 0) {
					delay_ms(10);
					press_time++;

					if (press_time > 60) {
						break;
					}
				}

				break;
			}
		}

		if (led_flash_cnt > 100) {
			led_flash_cnt = 0;
			bsp_toggleLed();
		} else {
			led_flash_cnt++;
		}
	}
	bsp_setLed(1);
	delay_ms(30);
	bsp_setLed(0);
	delay_ms(30);
	bsp_setLed(1);
	delay_ms(30);

	// lcd power on
	// bsp_lcd_io_initial();
	bsp_setVdd(1);
	bsp_setLed(1);
	lcd->io_initial();
	delay_ms(20);

	// check one click or double click
	// if double click goto test
	// lcd->test();
	// or goto aoi
	if (press_time > 50) {
		// bsp_sendString("Enter Test Mode\r\n");
		printf("Enter Test Mode\r\n");

		printf("Valid Screen Index:\r\n");
		for (int i = 0; i < MAX_SCREEN_COUNT; i++) {
			if (lcd->screen[i] != 0) {
				printf("%02x\r\n", i + 0x30);
			}
		}

		lcd->test();
	}

	// not a long press, enter AOI mode
	lcd->reset();
	delay_ms(50);

	lcd->initial();
	delay_ms(50);

	lcd->screen[0xf]();

	bsp_sendChar(0x3F);

	char ch = 0;
	press_time = 0;
	while (1) {

		if (bsp_getRxcpltFlag()) {

			ch = bsp_getChar();
		}

		if (ch != 0) {

			bsp_sendChar(ch);

			if (ch == 0x3e) {
				goto aoi_start;
			} else if (lcd->screen[ch - 0x30] != 0) {
				bsp_setLed(0);
				lcd->screen[ch - 0x30]();
				bsp_setLed(1);
			} else {
			}

			ch = 0;
		}

		if (bsp_getKey() == 0) {
			press_time += 1;
		}

		if (press_time > 100) {

			while(bsp_getKey() == 0) {
				bsp_setLed(1);
				delay_ms(50);
				bsp_setLed(0);
				delay_ms(50);
			}

			goto aoi_start;
		}

		delay_ms(5);
	}
}